package com.shanzmoo.merchant.server.api.config;

import com.shanzmoo.base.bean.SwaggerConfigBase;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.constant.ErrorCode;
import io.swagger.annotations.Api;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * swagger 配置
 * @author Gzhao
 * @date 2020/11/15
 */
@ConditionalOnExpression("${swagger.enable}")
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket adminDocket() {

        //添加全局响应状态码
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        Arrays.stream(ErrorCode.values()).forEach(errorEnums -> {
            responseMessageList.add(
                    new ResponseMessageBuilder()
                            .code(errorEnums.code())
                            .message(errorEnums.desc())
                            .responseModel(new ModelRef(errorEnums.desc()))
                            .build()
            );
        });
        responseMessageList.add(
                new ResponseMessageBuilder()
                        .code(Constant.SUCCESS_CODE)
                        .message("成功")
                        .responseModel(new ModelRef("成功"))
                        .build()
        );

        return new Docket(DocumentationType.SWAGGER_2)
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .forCodeGeneration(true)
                .groupName("platform-server-api")
                .apiInfo(SwaggerConfigBase.apiInfo("B端H5接口文档"))
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(SwaggerConfigBase.security())
                .securityContexts(SwaggerConfigBase.securityContexts())
                ;
    }

}
